<template>
  <div class="clearfix">
    <a-upload
      :action="upServer"
      :headers="headers"
      list-type="text"
      :file-list="fileList"
      :beforeUpload="beforeUpload"
      @change="handleChange"
      :disabled="disabled"
      :data="localData"
    >
   
    <div v-if="fileList.length < count && !disabled" >
      <a-button> <a-icon type="upload" /> 上传 </a-button>
    </div>
    </a-upload>
   
  </div>
</template>
<script>

import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import defaultSettings from '@/config/defaultSettings'
import request from '@/utils/request'
import {StringToJson} from '@/utils/util'

const uidGenerator=()=>{
    return '-'+parseInt(Math.random()*10000+1,10);
  }
const getFileName=(path)=>{
    if(path.lastIndexOf("\\")>=0){
      let reg=new RegExp("\\\\","g");
      path = path.replace(reg,"/");
    }
    return path.substring(path.lastIndexOf("/")+1);
}
const getDbFile=(path)=>{
  if(path.lastIndexOf("\\")>=0){
      let reg=new RegExp("\\\\","g");
      path = path.replace(reg,"/");
  }
  return path.substring(path.indexOf(defaultSettings.sdpFiles));
}

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  name:'LFileUpload',
  props:{
    value:{
      type:String,
      required:false
    },
    form:{
      type:Object,
      default:()=>{}
    },
    field:String,
    disabled:{
      type:Boolean,
      default:false
    },
    count:{
      type:Number,
      default:100
    },
    data:{
      type:[Object,String],
      default:()=>{}
    }
     
  },
  watch:{
    value(val){
      this.initFileList(val)
    }
  },
  created(){
    if(this.data){
        this.localData = StringToJson(this.data)
    }
    const token = storage.get(ACCESS_TOKEN)
    this.headers = {[`${ACCESS_TOKEN}`]:token}
    this.upServer = defaultSettings.uploadServer
    this.downServer = defaultSettings.downLoadServer
    this.initFileList()
    
  },
  data() {
    return {
      previewImage: '',
      fileList: [],
      headers:{},
      devServer:'',
      localData:{},
    };
  },
  methods: {
    handleChange(info) {
      let fileList = info.fileList
      if(info.file.status==='done'){
        if(info.file.response.success){
           fileList = fileList.map((file) => {
              if (file.response) {
                file.url = this.downServer+file.response.message;
              }
              return file;
            });
        }
      }else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`);
      }else if(info.file.status === 'removed'){
        this.handleDelete(info.file)
      }
      this.fileList = fileList

      if(info.file.status==='done' || info.file.status === 'removed'){
        this.handlePathChange()
      }
    },
    beforeUpload(file ){
      return true
    },
    initFileList(path){

      if(!path || path.length==0){
        this.fileList = [];
        return;
      }

      let fileList = [];
      let arr = path.split(",")
      for(var a=0;a<arr.length;a++){
        fileList.push({
            uid:uidGenerator(),
            name:getFileName(arr[a]),
            status: 'done',
            url:this.downServer+arr[a]
        })
      }
      this.fileList = fileList
    },
    handleDelete(file){
      //文件删除
      console.log(file)
    },
    handlePathChange(){
      let uploadFiles = this.fileList
      let path = ''
      if(!uploadFiles || uploadFiles.length==0){
        path = ''
      }
      let arr = [];
      for(var a=0;a<uploadFiles.length;a++){
        arr.push(getDbFile(uploadFiles[a].url))
      }
      if(arr.length>0){
        path = arr.join(",")
      }
      //更新值
      this.form.setFieldsValue({[`${this.field}`]: path})
    }
  },
  
};
</script>
<style scoped lang="less">
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: var(--text-color) !important;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: var(--text-color) !important;
}
.ant-upload-picture-card-wrapper {
  max-height:200px;overflow:auto;
}
.ant-upload-list-text {
  max-height:200px;overflow:auto;
}
.ant-upload-list-picture{
  max-height:200px;overflow:auto;
}
</style>